package com.graphsql.gamesdk.base;

import java.util.ArrayList;

import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.graphsql.gamesdk.R;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

public abstract class BasePullToRefreshFragment extends BaseFragment implements OnItemClickListener{

	protected ArrayList<?> mEntries = new ArrayList<Object>(1);

	protected PullToRefreshListView mAdapterView;

	protected MyAdapter mAdapter;

	// Only set adapter in main thread. deal with "adapter has changed" problem.
	// The child class should fill the mEntries list, and use mObjects list.
	protected ArrayList<?> mObjects = mEntries;

	protected int mViewId = R.id.gs_pull_refresh_list; // default is list

	@Override
	protected void onRefresh() {
		// refresh
		// 1. when listview item changed
		// 2. if has download job
		if (mObjects != mEntries) {
			mObjects = mEntries;
			if(mAdapter!=null)mAdapter.notifyDataSetChanged();
		}else{
			if(mAdapter!=null)mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onRefreshList() {
		mAdapter.notifyDataSetChanged();
	}

	protected void setView() {
		mAdapterView = (PullToRefreshListView) rootView.findViewById(mViewId);
	}

	protected void addListHeaderAndFooter() {
		//
	}

	protected void list() {
		if (mAdapter == null) {
			mAdapter = new MyAdapter();
			setView();
		}
		if(mViewId==R.id.gs_pull_refresh_list){
			((PullToRefreshListView)mAdapterView).setAdapter(mAdapter);
		}
	}

	@Override
	protected void init() {
		super.init();
		list();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	protected View getItemView(int position, View convertView, ViewGroup parent) {
		return null;
	}

	public class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			if (mObjects == null)
				return 0;
			return mObjects.size();
		}

		@Override
		public Object getItem(int position) {
			if (mObjects.size() > position) {
				return mObjects.get(position);
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (position >= getCount()) {
				return null;
			}
			return getItemView(position, convertView, parent);
		}

	}
	
	public int convertDpToPixel(float dp) {
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        float px = dp * (metrics.densityDpi / 160f);
        return (int) px;
    }

}
